<template>
  <pro-table
    ref="tableRef"
    class="plan-table"
    :table-data="tableData"
    :form-data="formData"
    row-key="id"
    :request="getData"
    :columns="columns"
    :pagination="true"
    :form-props="{ labelWidth: 80 }"
  >
    <template #operations="{ row }">
      <div class="grid-operate-wrap">
        <el-button
          type="primary"
          :disabled="getState(row) != '已生成'"
          link
          @click="getState(row) == '已生成' && downLoad(row)"
        >
          下载
        </el-button>
        <el-popconfirm title="确定删除吗？" @confirm="onDelete(row)">
          <template #reference>
            <el-button link type="danger"> 删除 </el-button>
          </template>
        </el-popconfirm>
      </div>
    </template>
    <template #appType="{ row }">
      {{ row.appType == 'redev' ? '二次开发' : '离线部署' }}
    </template>

    <template #handleState="{ row }">
      <div class="flexCenter">
        <span
          :class="[
            'round',
            (getState(row) == '已过期' || getState(row) == '生成失败') && 'fail-round',
            getState(row) == '生成中...' && 'wait-round',
          ]"
        ></span>
        {{ getState(row) }}
      </div>
    </template>

    <template #creationDate="{ row }">
      <div>{{ getPastTime(row.creationDate) }}</div>
    </template>

    <template #size="{ row }">
      <div class="flexCenter">{{ getMemory(row.size) }}</div>
    </template>
  </pro-table>
</template>
<script setup lang="ts">
import api from '@/api';
import { GetProListByMuCond } from '@/api/project';
import { deleteExpActRecord } from '@/api/scene';
import { getResPath } from '@/utils/cimup';
import { useRequest } from '@jl/common/composable';
import { Column, ProTable } from '@jl/element-plus';
import { messageUtil } from '@jl/element-plus/utils';
import { debounce } from 'lodash';
import { ref } from 'vue';

const { data: projectData, run: getProjectData } = useRequest<any, any>(GetProListByMuCond, {
  list: [],
});
const projectList = computed(() => {
  return [{ label: '全部', value: undefined }].concat(
    projectData.value.list.map((item: any) => {
      return {
        label: item.projectName,
        value: item.projectId,
      };
    })
  );
});
getProjectData({
  params: {
    index: 1,
    pageSize: 1000,
    blurStr: '',
    state: -1,
  },
});

const tableRef = ref<any>();
const tableData = ref<any>([]);
const formData = ref<any>();
const columns = computed<Column[]>(() => [
  {
    type: 'input',
    prop: 'id',
    label: '序号',
    width: 80,
    span: 8,
    visible: false,
    formProps: {
      visible: false,
    },
  },
  {
    type: 'input',
    prop: 'transId',
    label: '应用ID',
    span: 8,
    formProps: {
      visible: false,
    },
    width: 320,
    tableProps: {
      fixed: 'left',
    },
  },
  {
    type: 'input',
    prop: 'blurName',
    label: '应用名称',
    span: 6,
    visible: false,
  },
  {
    type: 'input',
    prop: 'name',
    label: '应用名称',
    span: 6,
    formProps: {
      visible: false,
    },
    width: 320,
  },
  {
    type: 'select',
    prop: 'projectId',
    label: '所属项目',
    span: 6,
    options: projectList.value,
    visible: false,
  },
  {
    type: 'slot',
    prop: 'appType',
    label: '应用类型',
    span: 8,
    formProps: {
      visible: false,
    },
  },

  {
    type: 'slot',
    prop: 'handleState',
    label: '状态',
    span: 8,
    formProps: {
      visible: false,
    },
  },
  {
    type: 'slot',
    prop: 'size',
    label: '文件大小',
    span: 8,
    formProps: {
      visible: false,
    },
  },
  {
    type: 'slot',
    prop: 'creationDate',
    label: '有效期至',
    span: 8,
    width: 180,
    formProps: {
      placeholder: '请选择时间',
      type: 'datetime',
      visible: false,
      format: 'YYYY-MM-DD HH:mm:ss',
      valueFormat: 'YYYY-MM-DD HH:mm:ss',
    },
  },
  {
    type: 'slot',
    prop: 'operations',
    label: '操作',
    width: 140,
    formProps: {
      visible: false,
      align: 'center',
    },
    tableProps: {
      fixed: 'right',
    },
  },
]);

const getData = async (params: any) => {
  const result = await api.scene.getExpActResoList(params);
  return {
    total: result.count,
    rows: result.list,
  };
};

//删除
const onDelete = debounce((row) => {
  deleteExpActRecord({ params: { transId: row.transId } }).then((res) => {
    messageUtil.success('删除成功');
    tableRef.value.refresh();
  });
}, 300);

const downLoad = (row: any) => {
  window.open(getResPath(row.downloadLink), '_blank', 'noopener');
};

//状态
const getState = (row: any) => {
  let result = '';
  // 获取当前时间搓
  let futureTime = new Date(row.creationDate).getTime() + 7 * 24 * 3600 * 1000;
  let currentTime = new Date().getTime();
  if (currentTime) {
    if (currentTime > futureTime) {
      result = '已过期';
    } else {
      switch (row.handleState) {
        case 31:
          result = '生成中...';
          break;
        case 32:
          result = '生成中...';
          break;
        case 33:
          result = '生成失败';
          break;
        case 34:
          result = '生成中...';
          break;

        case 35:
          result = '生成中...';
          break;
        case 36:
          result = '生成失败';
          break;
        case 37:
          result = '生成中...';
          break;
        case 38:
          result = '生成中...';
          break;
        case 39:
          result = '生成失败';
          break;
        case 40:
          result = '已生成';
          break;
      }
    }
  }
  return result;
};

const getPastTime = (date: string) => {
  let result = new Date(date).getTime() / 1000 + 7 * 24 * 3600;
  return formatTime(result, 'Y-M-D h:m:s');
};

const formatTime = (number: number, format: string) => {
  //转换日期
  var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
  var returnArr = [];
  var date = new Date(number * 1000);
  returnArr.push(date.getFullYear());
  returnArr.push(formatNumber(date.getMonth() + 1));
  returnArr.push(formatNumber(date.getDate()));
  returnArr.push(formatNumber(date.getHours()));
  returnArr.push(formatNumber(date.getMinutes()));
  returnArr.push(formatNumber(date.getSeconds()));
  for (var i in returnArr) {
    format = format.replace(formateArr[i], returnArr[i]);
  }
  return format;
};

//数据转化
const formatNumber = (n: any) => {
  n = n.toString();
  return n[1] ? n : '0' + n;
};

//获取内存
const getMemory = (size: any) => {
  let result = '';
  if (size < 1024 * 1024) {
    let sizeNum = (size / 1024).toFixed(2);
    result = `${sizeNum}KB`;
  } else if (size > 1024 * 1024 && size <= 1024 * 1024 * 1024) {
    let sizeNum = (size / 1024 / 1024).toFixed(2);
    result = `${sizeNum}MB`;
  } else if (size > 1024 * 1024) {
    let sizeNum = (size / 1024 / 1024 / 1024).toFixed(2);
    result = `${sizeNum}GB`;
  }
  return result;
};
onMounted(() => {});
const handleExport = () => {};
</script>

<style lang="less">
.flexCenter {
  display: flex;
  align-items: center;
  .round {
    width: 7px;
    height: 7px;
    border-radius: 50%;
    background: #00f763;
    margin-right: 5px;
  }
  .fail-round {
    background: #ff5454;
  }
  .wait-round {
    background: #faad14;
  }
}
</style>
